package day01;

import java.util.Arrays;

public class MyArrayList<E> {
    private int size = 0;
    private Object[] elementData = {};

    public boolean add(E e){
        ensureCapacity();
        elementData[size++] = e;
        return true;
    }
    public boolean add(int index, E e){
        if (index<0 || index>size){
            throw new IndexOutOfBoundsException("越界了:"+index);
        }
        if (index == size){
            return add(e);
        }
        ensureCapacity();
        for(int i=size-1; i>=index; i--){
            elementData[i+1] = elementData[i];
        }
        elementData[index] = e;
        size++;
        return true;
    }

    /**
     * 确认(ensure)容量(Capacity)
     */
    private void ensureCapacity() {
        if (size == 0){
            elementData = new Object[10];
        }
        if (size == elementData.length) {
            //oldCapacity 旧容量
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }
    public E get(int index){
        if (index <0 || index>=size){
            throw new IndexOutOfBoundsException("越界"+index);
        }
        return (E)elementData[index];
    }
    public E remove(int index){
        return null;
    }
    public int size(){
        return size;
    }

    /**
     * A,B,C,D
     * @return "[A, B, C, D]"
     */
    public String toString(){
        if (size==0) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder("[");
        builder.append(elementData[0]);
        for(int i=1; i<size; i++){
            builder.append(", ").append(elementData[i]);
        }
        return builder.append(']').toString();
    }
}
